<?php
declare (strict_types=1);

namespace app\controller;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class RpcClient
{
    public function call()
    {
        // 建立连接
        $connection = new AMQPStreamConnection('127.0.0.1', '5672', 'guest', 'guest', '/');
        // 获取信道
        $channel = $connection->channel();

        // 声明回调队列
        $callback_queue = $channel->queue_declare(
            'callback_queue', false, false, true, false);

        // RPC客户端请求的参数
        $corr_id = uniqid();
        $msg = new AMQPMessage('rpc client send message', [
            'correlation_id' => $corr_id,
            'reply_to' => 'callback_queue'
        ]);

        // 发送RPC请求
        $channel->basic_publish($msg, '', 'rpc_queue');

        // RPC服务端返回的内容
        $response = null;

        // 等待RPC回调
        $channel->basic_consume('callback_queue', '', false, false, false, false, function ($reply) use ($corr_id, &$response) {
            if ($reply->get('correlation_id') == $corr_id) {
                $response = $reply->body;
            }

            // 确认消息处理完成
            $reply->delivery_info['channel']->basic_ack($reply->delivery_info['delivery_tag']);
        });

        while (!$response) {
            $channel->wait();
        }

        // 输出RPC服务端返回的内容
        echo $response;

        // 关闭信道
        $channel->close();
        // 关闭连接
        $connection->close();
    }
}
